// Author: wsfuyibing <682805@qq.com>
// Date: 2025-05-01

package login

import (
	"context"
	"gitee.com/go-libs/result"
	"gitee.com/go-libs/validator-iris/validator"
	"gitee.com/go-wares/framework-iris/framework/src/logics"
	"github.com/kataras/iris/v12"
	"server/app/config"
	"server/app/http/logics/guest"
	"server/app/http/models"
	"server/app/kind"
	"server/app/lib"
)

// Logic
// 微信登录.
type Logic struct {
	request *Request

	openid string
	guest.Login
}

// New
// 创建逻辑实例.
func New() logics.Logical {
	return &Logic{
		request: &Request{},
	}
}

// Before
// 前置校验.
//
//  1. 校验入参.
//  2. 获取微信OpenId.
func (o *Logic) Before(ctx context.Context, i iris.Context) (err error) {
	if err = validator.Json(i, o.request); err == nil {
		o.openid, err = lib.Weixin.GetOpenId(ctx, o.request.Code)
	}
	return
}

// Run
// 登陆过程.
func (o *Logic) Run(ctx context.Context, _ iris.Context) result.Result {
	var (
		res     = result.New()
		err     error
		logined *guest.Logined
		oauth   *models.Oauth
	)

	// 1. 初始授权.
	if oauth, err = o.InitOauth(ctx, kind.OauthKindWeixin, config.WeiXin.GetAppId(), o.openid); err != nil {
		return res.WithError(err)
	}

	// 2. 直接登录.
	//    授权记录上已经绑定了用户账号, 直接使用此账号登录即可.
	if oauth.UserId.IsBound() {
		// 2.1 登录过程.
		if logined, err = o.InitLoginedForUser(ctx, oauth, o.request.Device); err != nil {
			return res.WithError(err)
		}

		// 2.2 登录完成.
		return res.With(logined)
	}

	// 3. 绑定业务.
	//    授权记录上未绑定用户账号, 允许前端操作绑定逻辑.
	if logined, err = o.InitLoginedForBind(ctx, oauth); err != nil {
		return res.WithError(err)
	}
	return res.With(logined)
}
